from emmongo import em_mongomanager as mongoManager
from sysdata import sys_base_data as sysBaseData
from LSTM.variableset import EMVar
import datetime
from emnoti import Noti
import pymongo
from emtencent import em_classified
from dateutil.parser import parse

def caculate_newday_hot_industry_shizi(maxcount=5):
    #
    cursor = mongoManager.db[mongoManager.COL_MODULE_DATA].find({'source': 'tc_industry'}).sort([('last_update_time',pymongo.DESCENDING), ('score',pymongo.DESCENDING)]).limit(maxcount)
    if cursor.count():
        l = list(cursor)
        total_stks = []
        [total_stks.extend(x['module_stk_codes']) for x in l]
        total_stks_single = set(total_stks)
        for code in total_stks_single:
            sfund = sysBaseData.get_self_fund(code)
            try:
                caculate_stk_shizi(code,insertDB=False, notiTag='实时热门板块')
            except Exception as e:
                print('%s 获取 异常，原因→→→→' % sfund.code_with_name())
                print(e)
                continue


def caculate_cixin_shizi():
    cixin_stks = em_classified.get_tc_concept_code_df(concept_id='021023')

    for index, item in cixin_stks.iterrows():
        try:
            sfund = sysBaseData.get_self_fund(item['code'])
            if sfund:
                ipo_year = sfund.ipodate[0]
                ipo_month = sfund.ipodate[1]
                throld_date = datetime.datetime.now() - datetime.timedelta(days=150)
                if ipo_year >= throld_date.year and ipo_month >= throld_date.month:
                    caculate_stk_shizi(sfund.stkcode, insertDB=False, notiTag='次新Module')
            else:
                print('本地自选为空')
        except Exception as e:
            print('%s 获取 异常，原因→→→→' % sfund.code_with_name())
            print(e)
            continue

    pass

def caculate_shizi():
    stks = mongoManager.db[mongoManager.COL_SELF_FUND].find().sort([('last_update_time',pymongo.DESCENDING), ('score',pymongo.DESCENDING)])
    l = list(stks)
    print('共有%s条数据' % len(l))
    t1 = datetime.datetime.now()
    count = 0
    for i in l:
        try:
            sfund = sysBaseData.get_self_fund(i['stk_code'])
            caculate_stk_shizi(i['stk_code'], insertDB=False)
        except Exception as e:
            print('%s 获取 异常，原因→→→→' % sfund.code_with_name())
            print(e)
            print('\n')
            continue
    t2 = datetime.datetime.now()
    totalsec = (t2 - t1).total_seconds()
    print('共花费时间 %ld' % (totalsec))


def caculate_stk_shizi(stkcode, insertDB=True,notiTag ='自选'):
    sfund = sysBaseData.get_self_fund(stkcode=stkcode)
    # sfund = sysBaseData.get_self_fund('600792')
    sfund.update_from_ts()
    if sfund.now < 12:
        raise Exception('当前价格小于12，不符合要求')
    day_data = sfund.get_index(start='2017-01-01', ktype='D', insertdb=insertDB)
    data = sfund.get_index(start='2011-01-01', ktype='60', append_now=True, indicator='shape', insertdb=insertDB)

    tmp = data.tail(10)
    aH2L = tmp[EMVar.ABS_HIGH2LOW] < 0.006
    aC2O = tmp[EMVar.ABS_CLOSE2OPEN] < 0.0006
    tmp_filter = tmp[aH2L & aC2O]
    if tmp_filter.shape[0]:
        shizi_price = tmp_filter.ix[-1][EMVar.close]
        shizi_datetime = tmp_filter.ix[-1].name
        shizi_dayhm = shizi_datetime.strftime(EMVar.FORMATE_YMD_HM)
        shizi_day = shizi_datetime.strftime(EMVar.FORMATE_YMD)
        delta = (datetime.datetime.now() - shizi_datetime)
        delta_days = delta.days
        delta_mins = int(delta.total_seconds() / 60)

        now_day = datetime.datetime.now().strftime(EMVar.FORMATE_YMD)
        open_hm = now_day + ' 09:30'
        delta_open = int((datetime.datetime.now() - parse(open_hm)).total_seconds())/60
        if delta_open < 10:
            if shizi_dayhm == open_hm:
                raise Exception('%s 开盘十字星不符合模型' % sfund.code_with_name())
        if delta_mins < -10:
            raise Exception('%s 当前60min 还没有走完' % sfund.code_with_name())
        if shizi_day in day_data.index:
            ajx_price = day_data.ix[shizi_day][EMVar.dm1_ajx_price]
            if ajx_price >= 0.09:
                raise Exception('%s 十字星当天涨停，模型不匹配' % sfund.code_with_name())
            # else:
            #     print('%s 十字星当天涨跌幅 %s' % (sfund.code_with_name(), ajx_price))
        if (sfund.jCache_now2close <= 0.09):
            now2shiziprice = (sfund.now - shizi_price) / shizi_price
            Noti.show('%s:十字星:%3.2f%%,现价%3.2f' % (sfund.code_with_name(), sfund.jCache_now2close * 100, sfund.now),
                      'Score:%s,Now2十字价:%3.2f%%,DeltaDays%d，Time:%s Tag:%s' % (
                      sfund.score, now2shiziprice * 100, delta_days, shizi_dayhm, notiTag))
            print('※※※※※※※※※※※\n%s发现十字星,今日涨跌幅 %3.2f%%, 距离十字星 %3.2f%% \nhttp://stockhtm.finance.qq.com/sstock/ggcx/%s.shtml\n※※※※※※※※※※※\n' % (
                sfund.code_with_name(), sfund.jCache_now2close * 100, now2shiziprice * 100, sfund.stkcode))
            return tmp_filter.ix[-1]
    return None

# caculate_newday_hot_industry_shizi()
# caculate_shizi()
caculate_cixin_shizi()
# caculate_stk_shizi('002871',insertDB=False)